﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text.RegularExpressions;
using Jungle.Code.Utils;
using Jungle.News;

namespace Jungle.News.WebControls
{
    public class PreNew : WebControl
    {
        private int newId;
        public int NewId { get { return newId; } set { newId = value; } }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            NewObject n = new NewObject();
            n.NewId = newId;
            n.GetById();

            writer.Write("<div>");
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "news_table");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "news_td");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);

            writer.AddAttribute("style", "color: #0071bc; font-size: 14px;");
            writer.AddAttribute(HtmlTextWriterAttribute.Href, UrlHelper.GetSiteUrl() + "/ru/new.aspx?i=" + n.NewId.ToString());
            writer.RenderBeginTag(HtmlTextWriterTag.A);
            writer.Write(n.PubDate.ToShortDateString() + " - " + n.Title + "&nbsp;");
            writer.RenderEndTag();

            string quickText = n.Description;
            quickText = Regex.Replace(quickText, "<[^>]*?>", string.Empty, RegexOptions.IgnoreCase);
            writer.Write("<div class=\"news_pre\">");

            if (quickText.Length < 250)
                writer.Write(quickText.Substring(0));
            else
                writer.Write(quickText.Substring(0, 250));
            writer.Write("</div>");

            writer.RenderEndTag();

            if (UrlHelper.GetRequestUrl().IndexOf("ru/main") == -1)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                writer.AddAttribute("class", "news_img");
                PrintImage(writer, n.Img);
                writer.RenderEndTag();
            }

            writer.RenderEndTag();
            
            writer.RenderEndTag();
            writer.Write("</div>");

            base.RenderContents(writer);
        }

        private HtmlTextWriter PrintImage(HtmlTextWriter writer, string imgUrl)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Src, UrlHelper.GetSiteUrl() + imgUrl);
            writer.AddAttribute(HtmlTextWriterAttribute.Align, "absmiddle");
            writer.RenderBeginTag(HtmlTextWriterTag.Img);
            writer.RenderEndTag();
            return writer;
        }
    }
}
